import { computed, onMounted, onUnmounted } from 'vue'
import { editorInfos } from '@/stores/editor'
import pinia from '@/stores/index'

import { NextLoading } from '@/utils/loading'
import { gloabl } from '@/stores/global'
import { useRoute, onBeforeRouteLeave } from 'vue-router'

import { message, Modal } from 'ant-design-vue'

const useSaveWork = (disableSideEffects = false) => {
  const globalStore = gloabl(pinia)
  const editorStore = editorInfos(pinia)
  const route = useRoute()
  let timer: any
  const currentWorkId = route.params.id as string
  const isDirty = computed(() => editorStore.isDirty)
  const saveIsLoading = computed(() => globalStore.isOpLoading('saveWork'))

  const saveWork = async (showMessage = false) => {
    await editorStore.saveWork(currentWorkId)
    if (showMessage) {
      message.success('保存成功', 2)
    }
  }
  if (!disableSideEffects) {
    onMounted(() => {
      editorStore.resetEditor()
      if (currentWorkId) {
        editorStore.getWork(parseInt(currentWorkId))

        timer = setInterval(() => {
          if (isDirty.value) {
            saveWork()
          }
        }, 1000 * 30)
      }

      NextLoading.done()
    })
    onUnmounted(() => {
      clearInterval(timer)
    })
    onBeforeRouteLeave((to, from, next) => {
      // 离开之前截图并保存
      // 未保存，截图保存
      if (isDirty.value) {
        Modal.confirm({
          title: '作品还未保存，是否保存？',
          okText: '保存',
          okType: 'primary',
          cancelText: '不保存',
          onOk: async () => {
            await saveWork()
            next()
          },
          onCancel() {
            next()
          }
        })
      } else {
        next()
      }
    })
  }
  return { saveWork, saveIsLoading }
}
export default useSaveWork
